/*
 * @author cai
 * @date   2015-12-22
 * 
 * 在需要推送消息的页面加载时引入initWebSocket.js,然后调用initWebSocket()函数
 * 与mina服务器建立WebSocket连接
 */
function initWebSocket() {
	//引入必要的js和css
	loadExtentFile("../js/toastr/toastr.js", "js");
	loadExtentFile("../js/sweetAlert/sweetalert.min.js", "js");
	loadExtentFile("../css/toastr/toastr.css", "css");
	loadExtentFile("../css/sweetAlert/sweetalert.css", "css");
	var uri = "ws://127.0.0.1:2333";
	//var uri = "ws://172.16.114.135:2333";
	//var uri="ws://192.168.191.1:2333";
	ws = new WebSocket(uri);
	ws.onopen = function () {
		console.log("[WebSocket#onopen]\n");
	}
	ws.onmessage = function (e) {
		console.log("[WebSocket#onmessage] Message: '" + e.data + "'\n");
		var regexp =new RegExp("\{.*\}");
		//toastr.options.closeButton = true;
		var messageJson = JSON.parse(regexp.exec(e.data));

		toastr.options = {
			"closeButton": true,
			"debug": false,
			"newestOnTop": false,
			"progressBar": false,
			"positionClass": "toast-top-right",
			"preventDuplicates": false,
			"onclick": null,
			"showDuration": null,
			"hideDuration": null,
			"timeOut": 0,
			"extendedTimeOut": 0,
			"showEasing": "swing",
			"hideEasing": "linear",
			"showMethod": "fadeIn",
			"hideMethod": "fadeOut"
		}
		var temp = "";
		var title = "";
		if (messageJson.alertType != null) {
			title = "<div align='center'><a target='_blank' href='http://localhost:8080/Waterworks/Alert/LinkToAlert.action?alertType=" + messageJson.alertType + "'><strong><font color='#0000FF'>" + "预警类型：" + messageJson.alertType + "</font></strong></a></div>"
				/*temp += messageJson.meaTime;*/
			temp += "最大值：" + messageJson.uppervalue + "<br>";
			temp += "最小值：" + messageJson.lowervalue + "<br>";
			temp += "当前值：" + messageJson.value + "<br>";
			temp += "已超过设计范围，请注意！";
			toastr.error(temp, title);
			/*toastr.options.onClick = function() { 
				
				window.location.href='http://localhost:8080/IrrigationAutomation/WaterDistribution/BAWaterGateInfo.action?watergateName='+messageJson.watergateName; 
				}*/
		}
		//alert("error");
	}
	ws.onclose = function (e) {
		console.log("[WebSocket#onclose]\n");
		sweetAlert("网络连接出错", "请检查您的网络然后重新加载网页", "error");
		// e.stop();
		if (ws) {
			ws.close();
			ws = null;
		};
		ws.onerror = function () {
			sweetAlert("网络连接出错", "请检查您的网络然后重新加载网页", "error");
			console.log("网络出现错误");
		};
	}
}

function loadExtentFile(filename, fileType) {
	if (fileType == "js") {
		var oJs = document.createElement('script');
		oJs.setAttribute("type", "text/javascript");
		oJs.setAttribute("src", filename); //文件的地址 ,可为绝对及相对路径
		document.getElementsByTagName("head")[0].appendChild(oJs); //绑定
	} else if (fileType == "css") {
		var oCss = document.createElement("link");
		oCss.setAttribute("rel", "stylesheet");
		oCss.setAttribute("type", "text/css");
		oCss.setAttribute("href", filename);
		document.getElementsByTagName("head")[0].appendChild(oCss); //绑定
	}
}